package com.sduept.nwld.dataserver.manager.etl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sduept.bigdata.fault.common.ETLDAO;
import com.sduept.bigdata.fault.protection.model.BxProtectDeviceAlarm;
import com.sduept.bigdata.fault.protection.service.ProtectDeviceAlarmPersistManager;
import com.sduept.cim.model.protection.ProtectionEquipment;
import com.sduept.core.dao.SuperDAO;
import com.sduept.generator.ObjectId;
import com.sduept.nwld.dataserver.manager.cim.BxCimManager;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.nwld.dataserver.model.edata.cim.bx.BxSubstation;
import com.sduept.utils.DateUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 所有包含：<严重误码><无有效帧><纵联码错 的都会被分拣到interrupt表
 * 所有包含：<通信><通道><通讯>
 * 且不包含 <XX正常 ><投XX通道><通道XX收信><通道XX通><装置通讯状态> 的会被分拣到 interrupt表
 * 其他都被分到device表
 */
@Slf4j
@Service
public class ProtectDeviceAlarmETLManager {
	
	@Autowired
	private SuperDAO dao;
	
	@Autowired
	private ETLDAO eDao;
	
	@Autowired
	private CimManager cm;
	
	@Autowired
	private BxCimManager bxCim;
	
	@Autowired
	private ProtectDeviceAlarmPersistManager pmanager;
	
	private static Pattern pattern1 = Pattern.compile(".*?(严重误码|无有效帧|纵联码错).*?");
	private static Pattern pattern2 = Pattern.compile(".*?(通信|通道|通讯).*?");
	private static List<Pattern> refuseRegexList = Arrays.asList(
			Pattern.compile(".*?正常"),
			Pattern.compile("投通道.{1,2}"),
			Pattern.compile("通道.{1,2}收信"),
			Pattern.compile("通道.{1,2}通"),
			Pattern.compile("装置通讯状态"));
	
	public  void receiveAndSaveAllData() {
		List<?> list = getAllSourceData();
		receiveAndSave(list);
	}
	public  void receiveAndSavePartData(String date) {
		List<?> list = getSourceData(date);
		receiveAndSave(list);
	}
	
	
	public List<?> getAllSourceData(){
		List <?>result = eDao.query("select mRID,mName,mProtectName,mMsg,mEventStartTime,mStartMs,mReceviceTime,mFinishMs,mValue,"
				+ "m103Group,m103Item,pt_id,mDevID,mStationID,mFdevID,mStationName from t_bx_protect_device_alarm order by mEventStartTime asc,mStartMs asc ");
		return result;
	}
	public List<?> getSourceData(String date) {
		String sql = "select mRID,mName,mProtectName,mMsg,mEventStartTime,mStartMs,mReceviceTime,mFinishMs,mValue,"
				+ "m103Group,m103Item,pt_id,mDevID,mStationID,mFdevID,mStationName from t_bx_protect_device_alarm where update_time=";
		List<?> result = eDao.query(sql + "'" + date + "' order by mEventStartTime asc,mStartMs asc ");
		return result;
	}
	public  void receiveAndSave(List<?> list) {
		ProtectEquipmentSave equipmentSave = new ProtectEquipmentSave(list);
		equipmentSave.saveToBean();
	}
	public class ProtectEquipmentSave{
		private List<?> list;
		private Map<String,ProtectionEquipment> map=new HashMap<String,ProtectionEquipment>();
		private Map<String,ProtectionEquipment> mNameMap=new HashMap<String,ProtectionEquipment>();
		private Map<String,BxSubstation> bxMap=new HashMap<String,BxSubstation>();
		public ProtectEquipmentSave(List<?> list) {
			super();
			this.list = list;
			init();
		}
		public void init(){
			List<ProtectionEquipment> protectionEquipments = cm.listAllProtectionEquipments();
			for(ProtectionEquipment equipemnt:protectionEquipments){
				map.put(equipemnt.getPtId(), equipemnt);
				mNameMap.put(equipemnt.getName(), equipemnt);
			}
			List<BxSubstation> bxSubstations = bxCim.listAllBxSubstations();
			for(BxSubstation station:bxSubstations){
				if(StringUtils.isNotEmpty(station.getCimName())){
					bxMap.put(station.getMname(), station);
				}
			}
		}
		private int getValue(String s) {
			if("告警".equals(s)||"2".equals(s)) {
				return 2;
			}else if("复归".equals(s)||"1".equals(s)){
				return 1;
			}
			return 0;
		}
		public void saveToBean(){
			List<BxProtectDeviceAlarm> equipments = new ArrayList<BxProtectDeviceAlarm>();
			for(Object obj : list){
				Object[] objs = (Object[]) obj;
				for(int i=0;i<objs.length;i++){
					if(objs[i]!=null&&"null".equals(objs[i].toString())){
						objs[i]=null;
					}
				}
				BxProtectDeviceAlarm alarm=new BxProtectDeviceAlarm();
				if(objs[0]!=null){
					alarm.setmRID(objs[0].toString());
				}else{
					alarm.setmRID(ObjectId.get().toString());
				}
				if(objs[1]!=null)alarm.setmName(objs[1].toString());
				if(objs[2]!=null)alarm.setmProtectName(objs[2].toString());
				if(objs[3]!=null)alarm.setmMsg(objs[3].toString());
				if(objs[4]!=null)alarm.setmEventStartTime(DateUtil.getDateByString(objs[4].toString(), DateUtil.pattern_ymdhms));
				if(objs[5]!=null)alarm.setmStartMs((int)objs[5]);
				if(objs[6]!=null)alarm.setmReceviceTime(DateUtil.getDateByString(objs[6].toString(), DateUtil.pattern_ymdhms));
				if(objs[7]!=null)alarm.setmFinishMs((int)objs[7]);
				if(objs[8]!=null)alarm.setmValue(getValue(objs[8].toString()));
				if(objs[9]!=null)alarm.setM103Group((int)objs[9]);
				if(objs[10]!=null)alarm.setM103Item((int)objs[10]);
				if(objs[11]!=null)alarm.setPt_id(objs[11].toString());
				if(objs[15]!=null){
					BxSubstation bxSubstation = bxMap.get(objs[15].toString());
					if(bxSubstation!=null){
						alarm.setmStationID(bxSubstation.getCimId());
					} else {
						log.warn("保护告警信号获取变电站失败，变电站："+objs[15].toString());
					}
				}
				ProtectionEquipment equipment=null;
				if(null!=alarm.getPt_id()){
					equipment = map.get(alarm.getPt_id());
				}else{
					equipment = mNameMap.get(alarm.getmName());
				}
				if(equipment!=null){
					if(!StringUtils.isEmpty(equipment.getId())){
						alarm.setmDevID(equipment.getId());
					}
				}
				equipments.add(alarm);
			}
			try {
				List<BxProtectDeviceAlarm> interrupts = new ArrayList<BxProtectDeviceAlarm>();
				List<BxProtectDeviceAlarm> others = new ArrayList<BxProtectDeviceAlarm>();
				dao.persistentBatch(BxProtectDeviceAlarm.class, equipments);
				log.info("更新保护开关量告警："+equipments.size());
				if(equipments!=null&&equipments.size()>0){
					
					for(BxProtectDeviceAlarm ba:equipments){
						if(isInterruptAlarmData(ba.getmMsg())) {
							interrupts.add(ba);
						}else {
							others.add(ba);
						}
					}
					pmanager.generateProtectionInterruptAlarmData(interrupts);
					pmanager.generateProtectionDeviceAlarmData(others);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	private boolean isInterruptAlarmData(String s) {
		if(StringUtils.isEmpty(s)) {
			return false;
		}
		Boolean status = null;
		Matcher m1 = pattern1.matcher(s);
		if(m1.matches()) {
			status = true;
		}else {
			Matcher m2 = pattern2.matcher(s);
			if(m2.matches()) {
				for(Pattern r:refuseRegexList) {
					Matcher m3 = r.matcher(s);
					if(m3.matches()) {
						status = false;
						break;
					}
				}
				if(status == null) {
					status = true;
				}
			}else {
				status = false;
			}
		}
		return status;
	}
}
